package com.ruiyi.adrobot.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruiyi.adrobot.domain.Area;
import com.ruiyi.adrobot.domain.Device;
import com.ruiyi.adrobot.domain.DeviceInfoPackage;
import com.ruiyi.adrobot.domain.common.ResultMsg;
import com.ruiyi.adrobot.domain.company.Company;
import com.ruiyi.adrobot.mongo.company.CompanyRepository;
import com.ruiyi.adrobot.service.device.DeviceService;
import com.ruiyi.adrobot.service.vpn.VpnService;
import com.ruiyi.adrobot.utils.LoggerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * Created by tao.zeng on 2017/8/2.
 */
@RestController
@RequestMapping("/device")
public class DeviceController {
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private CompanyRepository companyRepository;
    @Autowired
    private VpnService vpnService;

    @GetMapping("/get")
    public ResultMsg<DeviceInfoPackage> get(String appId, String accessToken, Integer fun, @RequestParam(value = "virtual", defaultValue = "true") Boolean virtual) {
        ResultMsg<DeviceInfoPackage> resultMsg = new ResultMsg<>();
        Company company = companyRepository.findByIdAndAccessToken(appId, accessToken);
        if (null == company || company.getDeadline() < new Date().getTime()) {
            LoggerUtil.info("AccessToken过期");
            return ResultMsg.error(1, "AccessToken过期");
        }
        DeviceInfoPackage deviceInfoPackage = new DeviceInfoPackage();
        Device device = deviceService.findRandomNotUsedDevice(fun, virtual);
        deviceInfoPackage.setBoard(device.getBoard());
        deviceInfoPackage.setBrand(device.getBrand());
        deviceInfoPackage.setDisplayId(device.getDisplayId());
        deviceInfoPackage.setDpi(device.getDpi());
        deviceInfoPackage.setImei(device.getImei());
        deviceInfoPackage.setModel(device.getModel());
        deviceInfoPackage.setOpenId(device.getOpenId());
        deviceInfoPackage.setOsApi(device.getOsApi());
        deviceInfoPackage.setResolution(device.getResolution());
        deviceInfoPackage.setVersionAndroid(device.getVersionAndroid());
        // 获取vpnHost
        JSONObject jsonObject = getVpn(null, null);
        if (null == jsonObject) {
            LoggerUtil.info("获取vpn失败");
            return ResultMsg.error(2, "获取vpn失败");
        }
        DeviceInfoPackage.VpnInfo vpnInfo = new DeviceInfoPackage.VpnInfo(jsonObject.getString("ip"), jsonObject.getString("username"), jsonObject.getString("password"), jsonObject.getInteger("province_id"), jsonObject.getInteger("city_id"));
        deviceInfoPackage.setVpnInfo(vpnInfo);
        resultMsg.setReturnInfo(deviceInfoPackage);
        return resultMsg;
    }

    private JSONObject getVpn(Integer provinceId, Integer cityId) {
        JSONObject jsonObject;
        int repeatTime = 0;
        do {
            repeatTime++;
            if (null != provinceId) {
                jsonObject = vpnService.switchIp(Area.PROVINCE, provinceId.toString());
            } else if (null != cityId) {
                jsonObject = vpnService.switchIp(Area.CITY, cityId.toString());
            } else {
                jsonObject = vpnService.switchIp(Area.ALL, null);
            }
            if (jsonObject.getInteger("status") == 0) {
                if (repeatTime == 3) {
                    return null;
                }
                LoggerUtil.info("切换vpn接口调用失败暂停1秒：" + jsonObject.getInteger("errno"));
                try {
                    SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } while (jsonObject.getInteger("status") == 0);
        return jsonObject;
    }

    @GetMapping("/buildDevices")
    public String buildDevices() {
        deviceService.resolveTxt();
        //deviceService.buildBaseDevices_v1();
        // 构建设备型号
        //deviceService.buildModels();
        //deviceService.updateVirtualTrueInfo();
        //deviceService.buildVirtualDevice();
        return "admin/robot_info_list";
    }

}
